package com.union.pay.ccb.utils;

import cn.hutool.crypto.SecureUtil;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 字段转换工具类
 *
 * @author Administrator
 * @date 2022/08/12
 */
@Slf4j
@Component
public class CcbConvertUtils {


    /**
     * 建行参数获取
     *
     * @param object 对象
     * @param md5    md5
     * @return {@link String}
     */
    public static String getCcbParam(Object object, boolean md5) {
        List<String> values = Lists.newArrayList();
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                // 判断如果不是算mac MD5 并且字段是PUB 跳过
                if (!md5 && "PUB".equalsIgnoreCase(field.getName())) {
                    continue;
                }
                values.add(String.format("%s=%s", field.getName(), (null == field.get(object)) ? "" : field.get(object)));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("转换建行参数错误 {} {}", md5, e.getMessage());
        }
        String value = String.join("&", values);
        if (md5) {
            return String.format("&MAC=%s", SecureUtil.md5(value));
        }
        return String.join("&", values);
    }


}
